package 数据结构.huffmancode;

import java.io.*;
import java.util.*;

public class HuffmanCode {
    public static void main(String[] args) {
   /*     String str = "i like like like java do you like a java";
        byte[] contentBytes = str.getBytes();
        //  System.out.println(contentBytes.length);

        byte[] bytes = huffmanZip(contentBytes);
        // System.out.println(Arrays.toString(bytes));

        byte[] decode = decode(huffmanCodes, bytes);
        System.out.println(new String(decode));*/


        //测试压缩文件
   /*     String srcFile = ("d://src.bmp");
        String desFile = ("d://dst.zip");

        zipFile(srcFile, desFile);
*/


        //测试解压文件
        String zipFile = "d://dst.zip";
        String dest = "d://dst.bmp";
        unZipFile(zipFile, dest);
        System.out.println("解压完毕");

   /*     List<Node> nodes = getNode(contentBytes);
        System.out.println(nodes);
        System.out.println("创建霍夫曼树");
        Node huffmanTreeRoot = crertHuffmanTree(nodes);
        System.out.println("前序输出");
        huffmanTreeRoot.priOrder();
        System.out.println(huffmanTreeRoot);
        System.out.println("测试是否生成了霍夫曼编码");
        getCodes(huffmanTreeRoot);
        System.out.println(huffmanCodes);
        byte[] zip = zip(contentBytes, huffmanCodes);
        System.out.println("huffmanCode" + Arrays.toString(zip));*/

    }

    //解压

    /**
     * @param zipFile 压缩方法
     * @param desFile 目标位置
     */
    public static void unZipFile(String zipFile, String desFile) {
        //定义文件的输入流
        InputStream is = null;
        ObjectInputStream ois = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(zipFile);
            ois = new ObjectInputStream(is);
            //读取霍夫曼数组
            byte[] huffmanBytes = (byte[]) ois.readObject();
            //读取霍夫曼编码表
            Map<Byte, String> huffmanCodes = (Map<Byte, String>) ois.readObject();
            byte[] bytes = decode(huffmanCodes, huffmanBytes);
            //将bytes数组写入目标文件
            os = new FileOutputStream(desFile);
            os.write(bytes);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                if (os != null)

                    os.close();
                assert ois != null;
                ois.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //编写方法,将一个文件进行压缩
    private static void zipFile(String srcFile, String dstFile) {
        //创建输出流
        FileOutputStream os = null;
        FileInputStream is = null;
        ObjectOutputStream oos = null;

        //创建输出流
        try {
            is = new FileInputStream(srcFile);
            //创建一个和源文件大小一样的byte[]
            byte[] b = new byte[is.available()];
            is.read(b);
            //获取文件对应的霍夫曼编码表,压缩
            byte[] huffmanZip = huffmanZip(b);
            //创建文件的输出流,存放压缩文件
            os = new FileOutputStream(dstFile);
            oos = new ObjectOutputStream(os);
            //这里使用对象流的方式写入这个霍夫曼的编码,为了以后加压的时候使用,恢复的时候使用
            oos.writeObject(huffmanZip);
            oos.writeObject(huffmanCodes);

        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {

            try {
                if (is != null)
                    is.close();
                assert os != null;
                os.close();
                assert oos != null;
                oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }


    //重点解码方法

    /**
     * @param huffmanCodes 霍夫曼编码表map
     * @param huffmanBytes 霍夫曼字节数组
     * @return
     */
    private static byte[] decode(Map<Byte, String> huffmanCodes, byte[] huffmanBytes) {

        //先得到霍夫曼树对应的二进制字符串
        StringBuilder stringBuilder = new StringBuilder();

        //将byte数组转成2进制的字符串
        for (int i = 0; i < huffmanBytes.length; i++) {
            byte b = huffmanBytes[i];
            boolean flag = (i == huffmanBytes.length - 1);
            stringBuilder.append(byteToBitString(!flag, b));
        }
        //把字符串安装指定的霍夫曼编码进行解码
        HashMap<String, Byte> map = new HashMap<>();
        for (Map.Entry<Byte, String> entry : huffmanCodes.entrySet()) {
            map.put(entry.getValue(), entry.getKey());
        }
        //System.out.println("map=" + map);
        //创建一个集合存放byte
        ArrayList<Byte> list = new ArrayList<>();
        for (int i = 0; i < stringBuilder.length(); ) {
            int count = 1;//计数
            boolean flag = true;
            Byte b = null;

            while (flag) {
                String key = stringBuilder.substring(i, i + count);
                if (count + i > stringBuilder.length()) {
                    break;
                }
                b = map.get(key);
                if (b == null) {
                    count++;
                } else {
                    flag = false;
                }
            }
            list.add(b);
            i += count;

        }
        //for循环结束,就全部完成了字符的存储
        byte b[] = new byte[list.size()];
        for (int i = 0; i < b.length; i++) {
            b[i] = list.get(i);
        }
        return b;

    }

    //完成数据解压 1.先转换成霍夫曼对应的二进制,2,对照霍夫曼编码从新转换成字符转

    /**
     * 讲一个byte 转传成一个二进制
     *
     * @param b
     * @return
     */
    private static String byteToBitString(boolean flag, byte b) {
        //使用变量保存b
        int temp = b;

        if (flag) {
            temp |= 256;
        }
        String str = Integer.toBinaryString(temp);
        if (flag) {
            return str.substring(str.length() - 8);
        } else {
            return str;
        }
    }

    //封装压缩功能

    /**
     * @param bytes 原始的字节数组
     * @return 压缩后
     */
    private static byte[] huffmanZip(byte[] bytes) {
        List<Node> nodes = getNode(bytes);
        //创建霍夫曼数
        Node huffmanTreeRoot = crertHuffmanTree(nodes);
        //根据霍夫曼数创建穿件编码
        Map<Byte, String> huffmanCOdes = getCodes(huffmanTreeRoot);
        //压缩,得到新的字节数组
        byte[] zip = zip(bytes, huffmanCOdes);
        return zip;

    }
    //编写一个方法,讲一个字符串对应的byte数组,通过生成的霍夫曼编码表,返回一个霍夫曼表码表处理过后的字节数组

    /**
     * @param bytes        这是原始的字符串对应的byte[]
     * @param huffmanCodes huffmanCodes 生成的霍夫曼编码map
     * @return 返回霍夫曼编码处理后的byte[]
     */
    private static byte[] zip(byte[] bytes, Map<Byte, String> huffmanCodes) {
        //1.利用huffmancodes将bytes转成霍夫曼编码对应的字符串
        StringBuilder stringBuilder = new StringBuilder();
        for (byte b : bytes) {
            stringBuilder.append(huffmanCodes.get(b));
        }
        //System.out.println("测试stringbufferder=" + stringBuilder);
        //统计返回byte[]
        int len;
        if (stringBuilder.length() % 8 == 0) {
            len = stringBuilder.length() / 8;
        } else {
            len = stringBuilder.length() / 8 + 1;
        }
        //创建存储压缩后的byte数组
        byte[] huffmanCodeBytes = new byte[len];
        int index = 0;
        for (int i = 0; i < stringBuilder.length(); i += 8) {//8位一个byte
            String strByte;
            if (i + 8 > stringBuilder.length()) {
                strByte = stringBuilder.substring(i);

            } else {
                strByte = stringBuilder.substring(i, i + 8);

            }
            huffmanCodeBytes[index] = (byte) Integer.parseInt(strByte, 2);
            index++;
        }
        return huffmanCodeBytes;
    }

    private static Map<Byte, String> getCodes(Node root) {
        if (root == null) {
            return null;
        }
        getCodes(root.left, "0", stringBuilder);
        getCodes(root.right, "1", stringBuilder);
        return huffmanCodes;
    }

    //霍夫曼编码表放在map中比较合适Map<Byte,Integer>{}
    //
    static Map<Byte, String> huffmanCodes = new HashMap<>();
    static StringBuilder stringBuilder = new StringBuilder();

    /**
     * 将传入的node节点的所有叶子节点的霍夫曼编码得到,并放入到huffmanCodes中
     *
     * @param node          传入的节点
     * @param code          路径:左子节点是0,右子节点是1
     * @param stringBuilder 用于拼接路径的
     */
    private static void getCodes(Node node, String code, StringBuilder stringBuilder) {
        StringBuilder stringBuilder2 = new StringBuilder(stringBuilder);
        stringBuilder2.append(code);
        if (node != null) {
            //判断当前node是节点还是非叶子节点
            if (node.date == null) {
                //说明是非叶子节点
                //想左递归
                getCodes(node.left, "0", stringBuilder2);
                //向有递归
                getCodes(node.right, "1", stringBuilder2);
            } else {
                //说明是一个叶子节点
                huffmanCodes.put(node.date, stringBuilder2.toString());
            }

        }

    }

    private static void preOreder(Node root) {
        if (root != null) {
            root.priOrder();
        } else {
            System.out.println("数据是空的");
        }
    }

    private static List<Node> getNode(byte[] bytes) {
        ArrayList<Node> nodes = new ArrayList<>();
        //,遍历bytes,统计出现次数,存储每一个byte出现的次数
        HashMap<Byte, Integer> counts = new HashMap<>();
        for (byte b : bytes) {
            Integer count = counts.get(b);
            if (count == null) {
                counts.put(b, 1);
            } else {
                counts.put(b, count + 1);
            }
        }
        //把每个键值对转成node对象,并加入Node集合;
        for (Map.Entry<Byte, Integer> entry : counts.entrySet()) {
            nodes.add(new Node(entry.getKey(), entry.getValue()));
        }
        return nodes;
    }

    //创建霍夫曼树
    private static Node crertHuffmanTree(List<Node> nodes) {
        while (nodes.size() > 1) {
            Collections.sort(nodes);
            //取出第一个
            Node leftNode = nodes.get(0);
            //2
            Node rigthNode = nodes.get(1);
            //创建一颗新树
            Node parent = new Node(null, leftNode.weight + rigthNode.weight);
            parent.left = leftNode;
            parent.right = rigthNode;
            //移除处理的二叉树
            nodes.remove(leftNode);
            nodes.remove(rigthNode);
            //加入新的二叉树
            nodes.add(parent);
        }
        return nodes.get(0);
    }


}

class Node implements Comparable<Node> {
    Byte date;
    int weight;//权值,表示字符出现的次数
    Node left;
    Node right;

    Node(Byte date, int weight) {
        this.date = date;
        this.weight = weight;
    }

    @Override
    public int compareTo(Node o) {
        return this.weight - o.weight;
    }

    @Override
    public String toString() {
        return "Node{" +
                "date=" + date +
                ", weight=" + weight +
                '}';
    }

    //前序遍历
    public void priOrder() {
        System.out.println(this);
        if (this.left != null) {
            this.left.priOrder();
        }
        if (this.right != null) {
            this.right.priOrder();
        }

    }


}

